﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Storage;
using System.IO;
using System.Xml.Serialization;

namespace StreetlightGames.SpaceShooter
{
    [Serializable]
    public class HighScoreData
    {
        /// <summary>
        /// Gets the FileName
        /// </summary>
        private static string FileName
        {
            get
            {
                string path = StorageContainer.TitleLocation;
                string fileName = Path.Combine(path, "HighScores.xml");
                return fileName;
            }
        }

        /// <summary>Gets or sets the Name value</summary>
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        private string _name;

        /// <summary>Gets or sets the Score value</summary>
        public int Score
        {
            get { return _score; }
            set { _score = value; }
        }
        private int _score;

        public static HighScoreData[] OpenScores()
        {
            HighScoreData[] data = null;
            if (!File.Exists(FileName))
            {
                data = new HighScoreData[0];
                return data;
            }
            XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData[]));
            FileStream stream = new FileStream(FileName, FileMode.Open);
            data = serializer.Deserialize(stream) as HighScoreData[];
            stream.Close();
            return data;
        }

        public static void Save(string name, int score)
        {
            List<HighScoreData> list = new List<HighScoreData>();
            list.AddRange(OpenScores());
            HighScoreData data = new HighScoreData();
            data.Name = name;
            data.Score = score;
            list.Add(data);
            list.Sort(
                delegate(HighScoreData data1, HighScoreData data2)
                {
                    return data2.Score.CompareTo(data1.Score);
                });
            while (list.Count > 10)
            {
                list.RemoveAt(10);
            }
            XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData[]));
            FileStream stream = new FileStream(FileName, FileMode.OpenOrCreate);
            serializer.Serialize(stream, list.ToArray());
            stream.Close();
        }

        internal static int GetHighScore()
        {
            HighScoreData[] data = OpenScores();
            if (data.Length == 0)
            {
                return 0;
            }
            return data[0].Score;
        }
    }
}
